<template>
    <div class="article-id-container">
        <div class="article-wrap">
            <h1 class="title">{{ articleData.title }}</h1>
            <!-- 作者信息区域 -->
            <van-cell
                class="aut-info"
                center
            >
                <van-image
                    slot="icon"
                    class="aut-img"
                    round
                    fit="cover"
                    :src="articleData.aut_photo"
                />
                <div slot="title" class="aut-name">{{ articleData.aut_name }}</div>
                <div slot="label" class="publish-time">{{ articleData.pubdate | relativeTime }}</div>
                <van-button
                    slot="default"
                    class="follow-btn"
                    :type="articleData.is_followed ? 'default' : 'danger'"
                    :icon="articleData.is_followed ? '' : 'plus'"
                    round
                    :loading="isFollowLoading"
                    @click="onFollow"
                >
                    {{ articleData.is_followed ? '已关注' : '关注' }}
                </van-button>
            </van-cell>
            <!-- 文章内容区域 -->
            <div class="markdown-body" ref="article-content" v-html="articleData.content"></div>
            <!-- 文章评论区域 -->
            <CommentList
                v-if="articleData.art_id"
                :source="articleData.art_id"
                :newItem="newItem"
                :commentListItemIndex="commentListItemIndex"
                @comment-count="commentCount=$event"
                @reply-click="onReplyClick"
            />
        </div>
        <!-- 底部区域 -->
        <div class="article-bottom">
            <van-button
                class="comment-btn"
                type="default"
                round
                size="small"
                @click="showWriteComment = true"
            >写评论
            </van-button>
            <div class="icon-box">
                <van-icon
                    name="comment-o"
                    :badge="commentCount"
                    color="#777"
                />
                <van-icon
                    :name="articleData.is_collected ? 'star' : 'star-o'"
                    :color="articleData.is_collected ? 'orange' : '#777'"
                    @click="onCollect"
                />
                <van-icon
                    :name="articleData.attitude === 1 ? 'good-job' : 'good-job-o'"
                    :color="articleData.attitude === 1 ? 'hotpink' : '#777'"
                    @click="onLike"
                />
                <van-icon
                    name="share"
                    color="#777"
                />
            </div>
        </div>
        <!-- 写评论的弹出层 -->
        <PostComment
            :target="articleId"
            :showWriteComment.sync="showWriteComment"
            @post-success="postSuccess"
        />
        <!-- 回复评论的弹出层 -->
        <van-popup
            class="replyComment"
            v-model="isReplyShow"
            position="bottom"
            get-container="body"
            safe-area-inset-bottom
            :close-on-click-overlay="false"
        >
            <ReplyComment
                :comment="replyComment"
                @close="isReplyShow=false"
                @post-success="commentListItemIndex={ index: $event, time: new Date() }"
            />
        </van-popup>
    </div>
</template>

<script>
import 'github-markdown-css';
import CommentList from 'com/articleId/comment_list';
import PostComment from 'com/articleId/post_comment';
import ReplyComment from 'com/articleId/reply_comment';
import { ImagePreview } from 'vant';
import * as Api from 'api/common';

export default {
    name: 'article-id',
    components: {
        CommentList,
        PostComment,
        ReplyComment
    },
    props: {},
    // 监控data中的数据变化
    watch: {
    },
    // 定义属性
    data () {
        return {
            articleData: {},
            commentCount: null,
            isFollowLoading: false,
            showWriteComment: false,
            newItem: {},
            isReplyShow: false,
            replyComment: {},
            commentListItemIndex: null
        };
    },
    // 计算属性，会监听依赖属性值随之变化
    computed: {
        articleId () {
            return this.$route.params.id;
        }
    },
    // 方法集合
    methods: {
        async getArticle () {
            const res = await Api.reqDev(`/v1_0/articles/${this.articleId}`);
            if (res.message === 'OK') {
                this.articleData = res.data;
                this.$nextTick(() => {
                    this.handlerPreviewImage();
                });
            }
        },
        handlerPreviewImage () {
            const articleContent = this.$refs['article-content'];
            const imgs = articleContent.querySelectorAll('img');
            let imgPaths = [];
            imgs.forEach((img, index) => {
                imgPaths.push(img.src);
                img.onclick = function () {
                    ImagePreview({
                        images: imgPaths,
                        startPosition: index
                    });
                };
            });
        },
        async onFollow () {
            this.isFollowLoading = true;
            const data = {
                target: this.articleData.aut_id
            };
            if (this.articleData.is_followed) await Api.reqDev(`/v1_0/user/followings/${this.articleData.aut_id}`, 'delete');
            else await Api.reqDev('/v1_0/user/followings', 'post', { data });
            this.articleData.is_followed = !this.articleData.is_followed;
            this.isFollowLoading = false;
        },
        async onCollect () {
            this.$toast.loading({
                duration: 0,
                message: '操作中...',
                forbidClick: true
            });
            const data = {
                target: this.articleData.art_id
            };
            try {
                if (this.articleData.is_collected) await Api.reqDev(`/v1_0/article/collections/${this.articleData.art_id}`, 'delete');
                else await Api.reqDev('/v1_0/article/collections', 'post', { data });
                this.articleData.is_collected = !this.articleData.is_collected;
                this.$toast.clear();
                this.$toast.success(`${this.articleData.is_collected ? '' : '取消'}收藏成功`);
            } catch (err) {
                console.log(err);
                this.$toast.clear();
                this.$toast.fail('操作失败');
            }
        },
        async onLike () {
            this.$toast.loading({
                duration: 0, // toast 提示一直存在，只能手动清楚
                message: '操作中...',
                forbidClick: true
            });
            const data = {
                target: this.articleData.art_id
            };
            try {
                if (this.articleData.attitude === 1) {
                    await Api.reqDev(`/v1_0/article/likings/${this.articleData.art_id}`, 'delete');
                    this.articleData.attitude = -1;
                } else {
                    await Api.reqDev('/v1_0/article/likings', 'post', { data });
                    this.articleData.attitude = 1;
                }
                this.$toast.clear();
                this.$toast.success(`${this.articleData.attitude === 1 ? '' : '取消'}点赞成功`);
            } catch (err) {
                console.log(err);
                this.$toast.clear();
                this.$toast.fail('操作失败');
            }
        },
        postSuccess (newObj) {
            this.newItem = newObj;
        },
        onReplyClick (commentItem) {
            console.log('onReplyClick', commentItem);
            this.replyComment = commentItem;
            this.isReplyShow = true;
        },
        test (index) {

        }
    },
    // 生命周期 - 创建完成（可以访问当前this实例）
    created () {
        this.getArticle();
    },
    // 生命周期 - 挂载完成（可以访问DOM元素）
    mounted () {
    }
};
</script>

<style lang='less' scoped>
.article-id-container {
    // padding: 14px;
    .article-wrap {
        position: fixed;
        left: 0;
        right: 0;
        top: 46px;
        bottom: 50px;
        overflow-y: auto;
        .title {
            font-size: 20px;
            color: #3a3a3a;
            background: #fff;
            margin: 0;
            padding: 14px;
        }
        .aut-info {
            .aut-img {
                width: 35px;
                height: 35px;
                margin-right: 8px;
            }
            .aut-name {
                font-size: 12px;
                color: #333;
            }
            .van-cell__label {
                margin-top: 0;
                .publish-time {
                    font-size: 12px;
                    color: #b4b4b4;
                }
            }
            .van-cell__value {
                .van-button--default {
                    color: #fff;
                    background: #d3d3d3;
                }
            }
            .follow-btn {
                width: 85px;
                height: 29px;
            }
        }
        .markdown-body {
            padding: 14px;
            background: #fff;
            /deep/ img {
                width: 100%
            }
        }
    }
    .article-bottom {
        display: flex;
        align-items: center;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        height: 50px;
        background: #fff;
        border-top: 1px solid #b3b3b3;
        .comment-btn {
            width: 120px;
            margin: 0 30px;
        }
        .icon-box {
            flex: 1;
            display: flex;
            justify-content: space-evenly
        }
    }
}
</style>
<style lang="less">
// .writeComment {
//     display: flex;
//     align-items: center;
//     height: 26%;
//     .comment-content {
//         flex: 1;
//         textarea {
//             font-size: 16px;
//         }
//     }
//     .submit {
//         font-size: 20px;
//         width: 50px;
//         margin: 0 10px;
//         color: rgb(14,166,216);
//     }
// }
.replyComment {
    height: 80%;
}
</style>

